package com.lpf;

import com.google.common.collect.ImmutableMap;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
public class GraphQLDataFetchers {

    // 定义了 books 和 authors 两个集合来模拟数据源
    private static final List<Map<String, String>> books = Arrays.asList(
            ImmutableMap.of("id", "book-1",
                    "name", "Harry Potter and the Philosopher's Stone",
                    "pageCount", "223",
                    "authorId", "author-1"),
            ImmutableMap.of("id", "book-2",
                    "name", "Moby Dick",
                    "pageCount", "635",
                    "authorId", "author-2"),
            ImmutableMap.of("id", "book-3",
                    "name", "Interview with the vampire",
                    "pageCount", "371",
                    "authorId", "author-3")
    );

    private static final List<Map<String, String>> authors = Arrays.asList(
            ImmutableMap.of("id", "author-1",
                    "firstName", "Joanne",
                    "lastName", "Rowling"),
            ImmutableMap.of("id", "author-2",
                    "firstName", "Herman",
                    "lastName", "Melville"),
            ImmutableMap.of("id", "author-3",
                    "firstName", "Anne",
                    "lastName", "Rice")
    );

    public DataFetcher getBookByIdDataFetcher() {
        return new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment dataFetchingEnvironment) {
                // 获取 id参数，然后根据id查找 books集合 并返回相应的 Book信息
                String bookId = dataFetchingEnvironment.getArgument("id");
                return books.stream().filter(book -> book.get("id").equals(bookId)).findFirst().orElse(null);
            }
        };
    }

    public DataFetcher getAuthorDataFetcher() {
        return new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment dataFetchingEnvironment) {
                // DataFetcher 会按照 GraphQL Schema 定义从外层向内层调用
                // 这里可以直接通过 DataFetchingEnvironment 获取外层 DataFetcher 查找到的数据(即关联的Book）
                Map<String, String> book = dataFetchingEnvironment.getSource();
                String authorId = book.get("authorId");  // 根据 authorId 查找作者信息
                return authors.stream().filter(author -> author.get("id").equals(authorId)).findFirst().orElse(null);
            }
        };
    }

    public DataFetcher listDataFetcher() {
        return new DataFetcher() {
            @Override
            public Object get(DataFetchingEnvironment dataFetchingEnvironment) {
                return books;
            }
        };
    }
}